﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ForgeCraft
{
    public class CmdWarp : Command
    {
        public override string name { get { return "warp"; } }
        public override string shortcut { get { return ""; } }
        public override string type { get { return "world"; } }
        public override bool consoleUsable { get { return false; } }
        public override Permission defaultRank { get { return Permission.Guest; } }
        public CmdWarp() { }

        public override void Use(Player p, string message)
        {
            if (message == "list" || message == "show" || message == "all")
            {
                string portaList = "";
                int warpCount = 0;

                foreach (KeyValuePair<BlockPosition, WarpInfo> kvp in Server.DBWarpList)
                {
                    if (kvp.Value.isPublic)
                    {
                        portaList += kvp.Value.warpName + ",";
                        warpCount++;
                    }
                }

                p.Message("There are " + Color.Help + warpCount + Color.Sys + " warps: " + portaList.TrimEnd(','));
            }
            else
            {
                // TODO: Need to sort differences between private and public warps having common names.
                foreach (KeyValuePair<BlockPosition, WarpInfo> kvp in Server.DBWarpList)
                {
                    if (kvp.Value.warpName == message)
                    {
                        int warpFreeBlocks = 0;

                        for (int i = 0; i < 120; i++) // Find a suitable spawning area.
                        {
                            if (p.currentWorld.GetBlock((int)kvp.Key.x, (byte)(kvp.Key.y + i), (int)kvp.Key.z).type == 0)
                            {
                                warpFreeBlocks++;

                                if (warpFreeBlocks == 3) // Is safe to spawn!
                                {
                                    p.ChunkAreaPlayer = 7;
                                    p.Send(PacketWriter.MakePositionAndLook(new Position((double)kvp.Key.x, (double)kvp.Key.y + i - 3, (double)kvp.Key.z)));
                                    return;

                                }
                            }
                        }

                        p.Message("Warp blocked - Can't send you there!");
                        break;
                    }
                }
            }


        }

        public override void Help(Player p)
        {
            p.Message(Color.Aqua + "/warp " + Color.Help + "- Lists the warps.");
        }
    }
}